import userApi from "@/api/acl/user"
import { Message } from "element-ui"

const state = {
  pageList: [],
  total: 0,
  roleList: [],
  roles:[]
}

const mutations = {
  SET_PAGELIST(state, data) {
    state.pageList = data.items
    state.total = data.total
  },
  SET_ROLES(state, data) {
    state.roleList = data.allRolesList
    state.roles = data.assignRoles
  }
}

const actions = {
  // 获取用户列表
  async getPageList({ commit }, params) {
    try {
      const res = await userApi.getPageList(params.page, params.limit, params)
      if (res && res.code === 20000) {
        commit('SET_PAGELIST', res.data)
      }
    } catch (error) {

      return Promise.reject('error')
    }
  },
  // 添加单个用户
  async getAddUser({ commit }, params) {
    try {
      const res = await userApi.add(params);
      console.log(res);
      if (res && res.code === 20000) {
        Message.success('添加成功')
        return Promise.resolve('成功')
      }
    } catch (error) {
      console.error(error);
      return Promise.reject('error')
    }
  },
  // 批量删除
  async removeUsers({ commit }, ids) {
    try {
      const res = await userApi.removeUsers(ids)
      if (res && res.code === 20000) {
        Message.success('批量删除成功')
        return Promise.resolve('成功')
      } else {
        return Promise.reject('失败')
      }
    } catch (error) {
      console.error(error);
      return Promise.reject('失败')
    }
  },
  // 单个删除
  async removeById({ commit }, id) {
    try {
      const res = await userApi.removeById(id)
      if (res && res.code === 20000) {
        Message.success('删除成功')
        return Promise.resolve('成功')
      } else {
        return Promise.reject('失败')
      }
    } catch (error) {
      console.error(error);
      return Promise.reject('失败')
    }
  },
  // 单个修改
  async update({ commit }, params) {
    try {
      const res = await userApi.update(params)
      if (res && res.code === 20000) {
        Message.success('修改成功')
        return Promise.resolve('成功')
      } else {
        return Promise.reject('失败')
      }
    } catch (error) {
      console.error(error);
      return Promise.reject('失败')
    }
  },
  // 获取某个用户的所有角色
  async getRoles({ commit }, userId) {
    try {
      const res = await userApi.getRoles(userId)
      if (res && res.code === 20000) {
        console.log(res.data);
        commit('SET_ROLES', res.data)
        
      }
    } catch (error) {
      console.error(error);
      return Promise.reject('失败')
    }
  },
  async assignRoles({commit},params){
    try {
      const res = await userApi.assignRoles(params.userId,params.roleId)
      if(res && res.code ===20000){
        Message.success('分配角色成功')
        return Promise.resolve('成功')
      }else {
        return Promise.reject('失败')
      }
    } catch (error) {
      console.error(error);
      return Promise.reject('失败')
    }
  }
}


const getters = {

}

export default {
  state,
  mutations,
  actions,
  getters,
  namespaced: true
}